package com.competition.utils.youpaiyun;

import com.UpYun;
import com.competition.resp.ResponseResult;
import com.upyun.UpException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class YPYUtil {

//    yBucketName: "image-zzyun" #服务名称
//yUserName: "czz" #授权用户
//yPassword: "4m26oeMgilElPVmmqDPXapxqv31EXZOd" #授权密码
//yCatalogue: "images/facility-agricultrue/" #上传的文件目录

    private static String yBucketName = "image-zzyun";

    private static String yUserName = "czz";

    private static String yPassword = "4m26oeMgilElPVmmqDPXapxqv31EXZOd";

    private static String yCatalogue = "images/facility-agricultrue/";

    private static UpYun upYun = new UpYun(yBucketName, yUserName, yPassword);

    public static ResponseResult uploadImg(MultipartFile file, String uploadPath, String suffix) throws IOException, UpException {
        String filename = UUID.randomUUID().toString()+"."+suffix;
        try{
           upYun.writeFile(yCatalogue+uploadPath+"/"+filename,file.getBytes(),false);
        }catch (IOException i){
            return new ResponseResult(500,"文件读取失败",filename);
        }catch (UpException u){
            return new ResponseResult(500,"文件上传失败",filename);
        }
        return new ResponseResult(200,"文件上传成功",filename);
    }

    public static ResponseResult deleteImg(String uploadPath,String fileName) throws IOException, UpException {
        Boolean result = null;
        try{
            result = upYun.deleteFile(yCatalogue + uploadPath + "/" + fileName);
        }
        catch (IOException i){
            return new ResponseResult(500,"文件读取失败",result);
        }catch (UpException u){
            return new ResponseResult(500,"文件删除失败",result);
        }
        return new ResponseResult(200,"文件删除成功",result);
    }

    public static void main(String[] args) throws IOException, UpException {
        long bucketUsage = upYun.getBucketUsage();
        System.out.println(bucketUsage);
        Map<String, String> fileInfo = upYun.getFileInfo("images/facility-agricultrue/");
        System.out.println(fileInfo);
        String apiDomain = upYun.getApiDomain();
        System.out.println(apiDomain);
        List<UpYun.FolderItem> folderItems = upYun.readDir("images/facility-agricultrue/");
        System.out.println(folderItems);
    }
}
